<?php
/**
* 2016年3月22日 10:47:58
* 图片上传类
*/
header("Content-Type:text/html; charset=utf-8");
class Upload extends MY_Controller
{
	
	function __construct()
	{
		parent::__construct();
		//加载Api模型
        $this->load->model('Api/WeixinApi_model','WeixinApi');
	}

  /**
   * [ajax上传更多图片]
   * @Author   zt
   * @DateTime 2018-06-05
   * @return   [type]     [description]
   */
  function ajax_more_img()
  {
    if (isset($_FILES['Filedata'])) {
      $img = array();

      foreach ($_FILES['Filedata']['name'] as $key => $value) {
        $filedata = array('name' => $value, 'tmp_name' => $_FILES['Filedata']['tmp_name'][$key]);
        $res = $this->upload_img($filedata);
        $res['code'] == 1 ? $img[] = array('name' => $value, 'url' => $res['url']) : '';
      }

      if (empty($img)) {
        $echo = array(
          'code' => 0,
          'msg' => '文件上传失败，请重试',
        ); 
      } else {
        $echo = array(
          'code'     => 1,
          'msg'      => '文件上传成功',
          'img_data' => $img,
        );
      }
    } else {
      $echo = array(
        'code' => 0,
        'msg' => '文件上传失败，请重试',
      );
    }
    
    echo json_encode($echo);
  }

	/**
	 * 上传图片到阿里云
	 * @return [type] [description]
	 */
	function upload_img($filedata){
			$this->load->library('Uploader/Uploader');
			$upload = new Uploader();
			$result = $upload->upload_aliyun($filedata['name'],$filedata['tmp_name']);
			if($result['error']==0){
				//上传成功
				$return = array(
					'code'=>1,
					'url'=>$result['url'],
					'msg'=>'图片已经上传成功',
					);
				//将图片添加到素材库
				$data[0] = array(
					'url'=>$result['url'],
					'create_time'=>date('Y-m-d H:i:s'),
					);
				$this->addImgLibrary($data);    //图片素材库
                // var_dump(1);die();
			}else{
				//上传失败
				$return = array(
					'code'=>0,
					'msg'=>'图片上传失败,请重试',
					);
			}
			return $return;
	}
	/**
	 * ajax上传文件流图片
	 * @return [type] [description]
	 */
	function ajax_upload(){
		$data = $_POST['imageData'];
		
		list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        
        $data = base64_decode($data);
        $path = dirname(APPPATH)."/static/image/";

        $filename = $this->getFileName();

        $filepath = $path.$filename;
        //创建一个新的图片文件
        $fopen = fopen($filepath, 'wb');
        //将文件流写入图片
        fputs($fopen, $data);
        //关闭资源
        fclose($fopen);

        $file = array(
            'name' => $filename,
            'tmp_name' => $filepath,
        );
        $return = $this->upload_img($file);
        //删除新增的图片
        unlink($filepath);
        echo json_encode($return);

	}
    /**
     * 设置文件（图片）名
     * [setFileName description]
     */
    function getFileName(){
      $image_name = md5(uniqid(rand())).".jpg"; 
      return $image_name;
    }
	/**
	 * 添加图片到素材库
	 * @param [type] $data [description]
	 */
	function addImgLibrary($data){
		foreach ($data as $key => $value) {
			$res = $this->db->insert('img_library',$data[$key]);
		}
	}
	/**
	 * ajax上传图片
	 * @return [type] [description]
	 */
	function ajax_upload_file(){
		if(isset($_FILES['Filedata'])){
			$return = $this->upload_img($_FILES['Filedata']);
			echo json_encode($return);
		}
	}
	/**
	 * 弹出上传页面
	 * @return [type] [description]
	 */
	function display(){
		$this->load->view('Api/customizeDialogPage_02');
	}
 	/**
     * Ueditor多图上传阿里云
     * @return [type] [description]
     */
    function uploadFiles(){
         $files = $_FILES;
         $files = $this->dealFiles($files);

        //定义一个空数组存放多图url地址
        $photourl = array();
        $data = array();
        for($i=0;$i<count($files);$i++){

            if(isset($files[$i])){
                $filedata = $files[$i];
                
                 $file = array(
                'name'=>$filedata['name'],
                'tmp_name'=>$filedata['tmp_name'],
                );
				//上传图片至阿里云
                $result = $this->upload_img($file);
                if($result['code']==0){
                    echo "上传失败";
                }else{
                    //将url存入数组
                    $photourl[$i]['url'] = $result['url'];
                }
            }
           }		
            		$array = array(
            			'photourl'=>$photourl,
            			);
                    //var_dump($photourl);die();
                    $this->load->view('Api/success',$array);
    }
    /**
     * 转换上传文件数组变量为正确的方式
     * @access private
     * @param array $files  上传的文件变量
     * @return array
     */
     function dealFiles($files) {
        $fileArray  = array();
        $n  = 0;
        foreach ($files as $key=>$file){
            if(is_array($file['name'])) {
                $keys       =   array_keys($file);
                $count      =   count($file['name']);
                for ($i=0; $i<$count; $i++) {
                    $fileArray[$n]['key'] = $key;
                    foreach ($keys as $_key){
                        $fileArray[$n][$_key] = $file[$_key][$i];
                    }
                    $n++;
                }
            }else{
               $fileArray[$key] = $file;
            }
        }
       return $fileArray;
    }
    /**
     * 上传单个文件
     * @return [type] [description]
     */
    function uploadOne(){
		$photourl = array();
        if(isset($_FILES['Filedata'])){
            $filedata = $_FILES['Filedata'];

            $file = array(
                'name'=>$filedata['name'],
                'tmp_name'=>$filedata['tmp_name'],
                );
                //上传图片至阿里云
                $result = $this->upload_img($file);
                //var_dump($url);die();
                if($result['code'] == 0){
                    echo -1;
                }else{
                    $photourl[0]['url']=$result['url'];
                    $array = array(
                    	'photourl'=>$photourl,
                    	);
                    $this->load->view('Api/success',$array);
                }
        }
    }
    /**
     * 添加素材库图片
     * @return [type] [description]
     */
    public function upload_library(){
       $url = $_POST['selected_imgs'];
       $url = explode(',', $url);
       $photourl = array();
       foreach ($url as $key => $value) {
           $photourl[$key]['url'] = $value;
       }
			$array = array(
                    'photourl'=>$photourl,
                   );
            $this->load->view('Api/success',$array);
    }
   	/**
     * ajxa获取素材库图片
     * @return [type] [description]
     */
    function getLibraryImg(){
    	$where = array(
    		'id >'=>0,
    		);
        $imglist = $this->WeixinApi->myQueryList('img_library',$where);
        foreach ($imglist as $key => $value) {
        	$imglist[$key]['show'] = "hide";

        }
        header("Content-Type:text/html; charset=utf-8");
        echo json_encode($imglist);
    }



     /**
     * 下载js上传的微信图片
     * @return [type] [description]
     */
    function downloadWxImage(){
        $post = file_get_contents("php://input");
        $post = json_decode($post,true);
        empty($post) ? $post = $this->input->post() : '';
        $this->load->model('Curl_model','curl');
        $media_id = $post['media_id'];
        $this->load->model('Token_model','token');
        $access_token = $this->token->getAccessToken();//获取token
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
        $fileinfo = $this->httpGet($url);
        // echo json_encode($fileinfo['body']);
        $path = dirname(APPPATH)."/static/image/";
        $filename = $this->getFileName();
        $filepath = $path.$filename;
        //创建一个新的图片文件
        $fopen = fopen($filepath, 'wb');
        //将文件流写入图片
        fputs($fopen, $fileinfo['body']);
        //关闭资源
        fclose($fopen);
        $file = array(
            'name' => $filename,
            'tmp_name' => $filepath,
        );
        $return = $this->upload_img($file);

        //删除新增的图片
        unlink($filepath);
        echo json_encode($return);
    }


     /**
     * curl get请求
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
        public function httpGet($url) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_NOBODY, 0); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        $package = curl_exec($curl);
        $httpinfo = curl_getinfo($curl);
        curl_close($curl);

        $imageAll = array_merge(array('header'=>$httpinfo),array('body'=>$package)); 
        return $imageAll;
    }




     /**
     * ajax上传文件流
     * 2017年4月11日 15:06:58
     * @return [type] [description]
     */
    function ajax_uploadFile(){
        $file = $_FILES['file'];
        // if ($file['size'] > 1024*30*1024)
        // {
        //     $return = array('code'=>0,'msg'=>'您上传的附件过大');
        // }
        // else
        // {
            $postfix_name=pathinfo($file['name'], PATHINFO_EXTENSION);//获取后缀名

            $file = array(
                'name' => $file['name'],
                'tmp_name' => $file['tmp_name'],
                'file_name'=>$file['name'],//文件名
                'type'=>$postfix_name,//后缀名
            );
           // print_r($file);die();
            //上传文件到阿里云
            $return = $this->upload_file($file,$file['name'],$postfix_name,$file['type']);
        // }

        echo json_encode($return);
    }


    /**
     * 设置文件名
     * 2017年4月11日 15:10:58
     * $postfix_name 后缀名
     * [setFileName description]
     */
    function getDownFileName($postfix_name){
      $file_name = md5(uniqid(rand())).".".$postfix_name.""; 
      return $file_name;
    }


    /**
     * 上传文件到阿里云
     * 2017年4月11日 15:30:58
     * $file_name 文件名 $postfix_name后缀名
     * @return [type] [description]
     */
    function upload_file($filedata,$file_name,$postfix_name,$fileType){
            $this->load->library('Uploader/Uploader');
            $upload = new Uploader();
            $result = $upload->upload_aliyunFile($filedata['name'],$filedata['tmp_name']);
            if($result['error']==0){
                //上传成功
                $return = array(
                    'code'=>1,
                    'url'=>$result['url'],
                    'msg'=>'文件已经上传成功',
                    );
                //将图片添加到素材库
                $data = array(
                    'url'=>$result['url'],
                    //'create_time'=>date('Y-m-d H:i:s'),
                    'file_name'=>$file_name,
                    'type'=>$postfix_name,
                    'type_img'=>$this->getType($fileType),
                    );
                $this->db->insert('file_library',$data);
                $id = $this->db->insert_id();//添加后得到的id
                //上传成功
                $return = array(
                    'code'=>1,
                    'file_id'=>$id,
                    'url'=>$result['url'],
                    'type_img'=>$fileType,
                    'msg'=>'文件上传成功',
                    'filename'=>$file_name
                    );
               // $this->addFileLibrary($data);
                // var_dump(1);die();
            }else{
                //上传失败
                $return = array(
                    'code'=>0,
                    'msg'=>'文件上传失败,请重试',
                    );
            }
            return $return;
    }

    function getType($type)
    {
        switch ($type)
        {
            case "doc":
            case "txt":
            case "docx":
                $type = "doc.png";
                break;
            case "wps":
            case "xls":
            case "xlsx":
                $type = "xls.png";
                break;
            case "pdf":
                $type = "pdf.png";
                break;
            case "zip":
            case "rar":
                $type = "rar.png";
                break;
            case "png":
            case "jpg":
            case "jpeg":
            case "webp":
            case "gif":
                $type = "jpg.png";
                break;

            default:
                break;
        }

        return $type;
    }
    /**
     * 添加文件到素材库
     * 2017年4月11日 15:31:58
     * @param [type] $data [description]
     */
    // function addFileLibrary($data){
    //     foreach ($data as $key => $value) {
    //         $res = $this->db->insert('file_library',$data[$key]);
    //     }
    // }
    // 
    
    function ajax_upload_img()
    {
        $img_file = $_FILES['file'];

        $file = array(
            'name' => $img_file['name'],
            'tmp_name' => $img_file['tmp_name'],
        );
        $return = $this->upload_img($file);

        echo json_encode($return);
    }
}